// 这里没用React.lazy，是因为它没法配合vite的热加载动态更新组件，所以替换成 '@loadable/component'，它可以
// import {lazy} from 'react';
import loadable from '@loadable/component';
import pMinDelay from 'p-min-delay';

import Loading from '@/components/Loading';
import {
    LOGIN, NOTFOUND, HOME,
} from '@/config/url';

const Login = loadable(() => import('@/pages/Login'), { fallback: <Loading/> });
const NotFound = loadable(() => import('@/pages/NotFound'), { fallback: <Loading/> });
const Home = loadable(() => import('@/pages/Home'), { fallback: <Loading/> });

// 确保url唯一，在渲染路由是url充当的是组件的key
export const baseRouters = [
    {
        url: LOGIN,
        icon: '',
        label: '欢迎登录',
        component: Login,
        showInMenu: false, // 是否展示在菜单上
    },
    {
        url: NOTFOUND,
        icon: '',
        label: '404',
        component: NotFound,
        showInMenu: false,
    },
    {
        url: HOME,
        icon: '',
        label: '首页',
        component: Home,
        showInMenu: false,
    },
];

/**
 *获取有权限的路由
 *
 * @param {*} [routers=[]]
 * routers: {
 *      code: 'xxx-xxx-xxx', // 根据code映射组件路径permission-manage
 *      children: [], // 子路由
 *      icon: '', // 页面菜单的icon
 *      label: '', // 页面菜单的名称
 *      layout: '', // 页面的布局名称
 *      showInMenu: '', // 是否展示在菜单上
 *      rest, // 其他数据
 * }
 * @return {*} 一维路由数组
 */
export const addDynamicRoute = (routers=[]) => {
    const pages = import.meta.glob('@/pages/*/index.jsx');

    return routers.map(item => {
        const params = item.code.split('-'),
            pageUrl = params.join('/'),
            filePath = params.map(i => i.charAt(0).toUpperCase() + i.slice(1)).join('/'),
            path = `/src/pages/${filePath}/index.jsx`,
            component = pages[path] ? loadable(pages[path], { fallback: <Loading/> }) : <Loading tip="配置与资源不符，请联系技术同学处理"/>;

        if(Array.isArray(item.children) && item.children.length) {
            item.children = addDynamicRoute(item.children);
        }

        return (
            {
                url: `${BASEDIR}/${pageUrl || ''}`,
                icon: item.icon || '',
                label: item.name || '',
                component,
                layout: null,
                showInMenu: false,
            }
        );
    })
};
